package com.xatz.scanner

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.xatz.scanner.databinding.ActivityLoginBinding
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.io.StringReader


/**
 * author: tdq
 * date: 2021/7/20
 * description:
 */
class LoginActivity : AppCompatActivity(), View.OnClickListener {

    private val mService by lazy {
        ScannerRetrofitClient().getService(
            ScannerService::class.java,
            ScannerService.baseUrl
        )
    }

    private lateinit var sharedPreferences: SharedPreferences

    private lateinit var edit: SharedPreferences.Editor

    private lateinit var mBinding: ActivityLoginBinding

    private val netProgressDialog by lazy { NetProgressDialog(this) }

    @SuppressLint("CommitPrefEdits")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sharedPreferences = getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
        edit = sharedPreferences.edit()
        mBinding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        mBinding.btnLogin.setOnClickListener(this)
        if (sharedPreferences.getBoolean(Constant.isLogin, false)) {
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btnLogin -> {
                val username = mBinding.etCount.text?.trim().toString()
                val password = mBinding.etPassword.text?.trim().toString()

                if (username.isEmpty()) {
                    Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show()
                    return
                }

                if (password.isEmpty()) {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show()
                    return
                }
                netProgressDialog.show()
                webLogin(username, password)
            }
        }
    }

    private fun webLogin(username: String, password: String) {
        mService.login(username, password).enqueue(object : Callback<String> {
            override fun onResponse(call: Call<String>, response: Response<String>) {
                if (response.isSuccessful) {
                    response.body()?.let { parseXMLWithPull(it) }
                    Toast.makeText(this@LoginActivity, "登录成功", Toast.LENGTH_SHORT).show()
                    edit.putBoolean(Constant.isLogin, true)
                    edit.commit()
                    startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                    finish()
                } else {
                    Toast.makeText(
                        this@LoginActivity,
                        response.errorBody()?.string(),
                        Toast.LENGTH_SHORT
                    ).show()
                }
                netProgressDialog.closeDialog()
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                netProgressDialog.closeDialog()
                Timber.e(t)
                Toast.makeText(
                    this@LoginActivity,
                    "登录失败",
                    Toast.LENGTH_SHORT
                ).show()
            }

        })
    }

    private fun parseXMLWithPull(xmlData: String) {
        try {
            val xmlPullParser = XmlPullParserFactory.newInstance().newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "emp_cd" -> {
                                edit.putString(Constant.userAccount, xmlPullParser.nextText())
                                edit.commit()
                            }
                            "emp_name" -> {
                                edit.putString(Constant.userName, xmlPullParser.nextText())
                                edit.commit()
                            }
                            "bz" -> {
                                edit.putString(Constant.userBz, xmlPullParser.nextText())
                                edit.commit()
                            }
                        }
                    }
                    XmlPullParser.END_TAG -> {
                    }
                }
                eventType = xmlPullParser.next()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        Timber.e(keyCode.toString())
        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}